package cn.walls1717.wallsmall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.walls1717.wallsmall.common.utils.PageUtils;
import cn.walls1717.wallsmall.common.utils.Query;
import cn.walls1717.wallsmall.product.dao.BrandDao;
import cn.walls1717.wallsmall.product.entity.BrandEntity;
import cn.walls1717.wallsmall.product.service.BrandService;
import cn.walls1717.wallsmall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 分页查询与条件查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils listPages(Map<String, Object> params) {
        LambdaQueryWrapper<BrandEntity> lqw = new LambdaQueryWrapper<>();
        // 查询条件，根据品牌id或者品牌名称查询
        String key = ((String)params.get("key"));
        if (!StrUtil.isEmpty(key)) {
            // WHERE (brand_id = ? OR name LIKE ?)
            lqw.eq(BrandEntity::getBrandId, key).or().like(BrandEntity::getName, key);
        }
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), lqw);
        return new PageUtils(page);
    }

    /**
     * 修改品牌信息同时修改相关联的所有信息，保证冗余字段的数据一致性
     *
     * @param brand 品牌参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDetail(BrandEntity brand) {
        // 更新本身brand表
        updateById(brand);
        if (!StrUtil.isEmpty(brand.getName())) {
            // 更新category_brand_relation表
            categoryBrandRelationService.updateBrandNameByBrandId(brand.getBrandId(), brand.getName());
            // TODO 更新其他冗余字段
        }
    }
}